package com.soulkun.smarthome.ui.main.home.popup

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableArrayList
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.LinearLayoutManager
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppPopupMainHomeFamilyBinding
import com.soulkun.smarthome.databinding.AppRecycleItemMainHomeFamilyListBinding
import com.soulkun.smarthome.logic.vo.FamilyVO
import com.soulkun.smarthome.ui.main.home.AppMainHomeFragment
import com.soulkun.smarthome.ui.main.home.adapter.AppMainHomeFamilyListAdapter
import com.soulkun.smarthome.ui.main.home.viewmodel.AppMainHomeViewModel
import soulkun.library.utils.logE

class AppMainHomeFamilyPopupWindow(
    context: Context,
    private val fragment: AppMainHomeFragment,
    private val viewModel: AppMainHomeViewModel
) : PopupWindow(context) {

    private val mBinding: AppPopupMainHomeFamilyBinding = DataBindingUtil.inflate(
        LayoutInflater.from(context),
        R.layout.app_popup_main_home_family,
        null,
        false
    )

    private val layoutManager = LinearLayoutManager(context)

    private val adapter by lazy {
        AppMainHomeFamilyListAdapter(context, viewModel.familyList) { binding ->
            View.OnClickListener {
                viewModel.selectFamily(
                    (binding as AppRecycleItemMainHomeFamilyListBinding).familyVO!!,
                    onComplete = {
                        fragment.setFamilyViewPager2()
                    },
                    onRoomEmpty = {
                        fragment.setRoomEmptyViewPager2()
                    })
                dismiss()
            }
        }
    }

    init {
        contentView = mBinding.root
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        width = ViewGroup.LayoutParams.MATCH_PARENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isFocusable = true
        isOutsideTouchable = true
        mBinding.rvMainHomeFamilyListFamily.layoutManager = layoutManager
        mBinding.rvMainHomeFamilyListFamily.adapter = adapter
    }

    override fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
        viewModel.maskShowStatus.set(true)
        super.showAtLocation(parent, gravity, x, y)
    }

}